package com.info.zhiduoduo.core.service.common;

import com.info.zhiduoduo.common.configs.DocConfig;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.utils.seal.SealUtil;
import com.info.zhiduoduo.core.formbean.SealFormBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tianyonghong
 * @create 2022/3/1
 */
@Slf4j
@Service
public class SealService {

    @Autowired
    DocConfig docConfig;

    /**
     * 公章图片后缀名
     */
    private String SEAL_NAME_SUFFIX = "_seal.png";

    /**
     * 生成企业/创客公章
     *
     * @param compname
     * @param username
     */
    public SealFormBean createCompOrUserSeal(String compname, String username) {
        SealFormBean sealFormBean = new SealFormBean();

        if (StringUtils.isNotBlank(compname)) {
            sealFormBean.setCompsealFile(createSeal(compname));
        }
        if (StringUtils.isNotBlank(username)) {
            sealFormBean.setUsersealFile(createSeal(username));
        }
        return sealFormBean;
    }

    /**
     * 批量生成公章
     */
    public Map<String, File> createSeals(String... sealnames) {
        Map<String, File> map = new HashMap();
        for (String name : sealnames) {
            if(StringUtils.isNotBlank(name)) {
                map.put(name, createSeal(name));
            }
        }
        return map;
    }

    /**
     * 生成公章，返回文件
     *
     * @param sealName
     * @return
     */
    public File createSeal(String sealName) {
        File sealPath = new File(docConfig.getSealPath());
        if (!sealPath.exists()) {
            sealPath.mkdirs();
        }
        File sealFile = new File(sealPath, sealName + SEAL_NAME_SUFFIX);
        if (!sealFile.exists()) {
            boolean create = SealUtil.createSimpleCircleSeal(sealName, sealFile.getAbsolutePath());
            if (!create) {
                throw new SmartException(StatusMsg.StatusMsg_199);
            }
        }
        return sealFile;
    }
}
